from apps.tax_policy.tax_policy.items import NetTaxPolicyItem
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import make_item
from utils.tools import urlencode, urldecode, parse_url_params


class HenanJzswzxrmzf5864Policy(BaseTaxPolicySpider):
    name = "henan_jzswzxrmzf_5864_policy"
    province: str = "河南省"  # 取表格
    city: str = "焦作市"  # 取表格
    county: str = "武陟县"  # 取表格
    park: str = ""  # 取表格
    source: str = "焦作市武陟县人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.wuzhi.gov.cn/wzx/cms/631"  # 注明入口网址，以便后续排错
    auto_next: bool = True

    def start_requests(self):
        url = "http://www.wuzhi.gov.cn/wzx/cms/631?page=1"
        yield self.Request(url, callback=self.parse_page)

    def parse_page(self, response, **kwargs):
        yield from self.parse_list(response, **kwargs)
        page_num = int(response.xpath('//a[contains(text(), "尾页")]/@href').re_first(r"page=(\d+)"))
        for i in range(1, page_num + 1):
            root_url, params = parse_url_params(response.request.url)
            params["page"] = i
            new_url = root_url + "?" + urlencode(params)
            yield self.Request(new_url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        for url in response.xpath('//a/@href').extract():
            yield response.follow(url, callback=self.parse_content)

    def parse_content(self, response, **kwargs):
        pre_data = self.parse_title_and_publish_time_by_gen(response.text)
        title = pre_data.get("title")
        publish_date = (
                response.xpath('//*[@name="PubDate"]/@content').get()
                or response.xpath('//*[@name="pub_date"]/@content').get()
                or pre_data.get("publish_time")
        )
        content = response.text
        content = self.process_content(content)

        item = dict(
            title=title,
            publish_date=publish_date,
            content=content,
            source_url=response.url,
            source=self.source,
            province=self.province,
            city=self.city,
            county=self.county,
            park=self.park,
        )
        if item["publish_date"]:
            yield make_item(NetTaxPolicyItem, item)


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_jzswzxrmzf_5864_policy".split())
